// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV,
    traceUser: true
})

const db = cloud.database()
const Users = db.collection('Users')

// 格式化返回json数据
function rjson (code,msg,data) {
    return { code, msg, data }
}



// 云函数入口函数
exports.main = async (event, context) => {
    console.log("打印接收到的数据: ", event)
    const  username = event.username;
    const app = new TcbRouter({ event });
    const { OPENID } = cloud.getWXContext();

    // 新增用户信息
    app.router('add', async (ctx) => {
        console.log("接收到的数据", event)
        let result = await Users.add({
            data: {
                _openid: OPENID,
                nickname: event.nickname,
                avatar: event.avatar,
                create_time: new Date(),
                update_time: new Date(),
                status: 1
            }
        })
        console.log("新增用户信息: ", result)
        if (result.hasOwnProperty('_id')) {
            ctx.body = rjson(1, 'success', '')
        } else {
            ctx.body = rjson(0, 'fail', '')
        }
    });

    // 更新用户资料
    app.router('update', async (ctx) => {
        console.log("[update]传入数据: ", username)
        let result = await Users.where({
            _openid: OPENID
        })
        .update({
            data: {
                nickname: username,
                update_time: new Date(),
            }
        })
        // stats
        console.log("更新结果: ", result)
        if (result.stats.updated == 1) {
            ctx.body = rjson(1, 'success', '')
        } else {
            ctx.body = rjson(0, 'fail', '')
        }
        
    });

    // 查询用户信息
    app.router('login', async (ctx) => {
        let result = await Users.where({
            _openid: OPENID
        })
        .get()
        console.log("用户登录信息: ", result.data)
        if (result.data.length == 1) {
            // 获取到用户的数据
            ctx.body = rjson(1, 'success', result.data[0]);
        } else {
            ctx.body = rjson(0, 'fail');
        }
    });
    
    return app.serve();
}


// const getOpenId = require('./getOpenId/index')
// const query = require('./query/index')
// const complete = require('./complete/index')

// exports.main = async (event, context) => {
//     switch (event.type) {
//         case 'getOpenId':
//             return await getOpenId.main(event, context);
//         case 'query':
//             return await query.main(event, context);
//         case 'complete':
//             return await complete.main(event, context);
//     }
// }